from functools import wraps

from django.core.cache import cache
from django.shortcuts import redirect, render

PAGE_CACHE_KEY = 'pagecache:%s'


def my_page_cache(timeout):
    """实现页面缓存的装饰器"""

    def wrapper1(view_func):

        def wrapper2(request):
            if request.method == 'GET':
                key = PAGE_CACHE_KEY % request.get_full_path()
                response = cache.get(key)
                if not response:
                    response = view_func(request)
                    cache.set(key, response, timeout)
            else:
                response = view_func(request)
            return response

        return wrapper2

    return wrapper1


def login_required(view_func):
    """检查用户是否登录的装饰器"""

    @wraps(view_func)
    def wrapper(request):
        if request.session['login_user']:
            return view_func(request)
        else:
            return redirect('/user/login/')

    return wrapper


def check_perm(perm_name):
    """检查用户是否具有操作权限的装饰器"""

    def wrapper1(view_func):

        def wrapper2(request):
            user = request.session['login_user']

            if user.has_perm(perm_name):
                return view_func(request)
            else:
                return render(request, '403.html')
        return wrapper2

    return wrapper1
